let express = require('express');
let router = express.Router();
let systemInstall  = require('../../common/install_action');
let createSql  =  require('../../common/create_sql.js');


//渲染安装 协议说明界面
router.get('/' ,async function (req,res) {
  await res.render('install/install')  
})

//渲染安装信息填写界面
router.get('/index',async function(req,res){
  await res.render('install/message')
})

//安装信息提交
router.post('/' ,async function(req,res){
  let sqlAddress =req.body.sqlAddress;
  let sqlName = req.body.sqlName;
  let sqlUser = req.body.sqlUser;
  let sqlPwd = req.body.sqlPwd;
  let companyName = req.body.companyName;
  let userName = req.body.userName;
  let userPwd  = req.body.userPwd;
  if(!sqlAddress){
    return await res.json({status:203,msg:"请输入数据库服务器地址！"})
  }
  if(!sqlName){
    return await res.json({status:203,msg:"请输入数据库名！"})
  }
  if(!sqlUser){
    return await res.json({status:203,msg:"请输入数据库用户名！"})
  }
  if(!sqlPwd){
    return await res.json({status:203,msg:"请输入数据库密码！"})
  }
  if(!companyName){
    return await res.json({status:203,msg:"请输入公司名称！"})
  }
  if(!userName){
    return await res.json({status:203,msg:"请输入管理员账号！"})
  }
  if(!userPwd){
    return await res.json({status:203,msg:"请输入管理员密码！"})
  }
  let  params = req.body;
  params.installStatus='';

  let systemInstll=  await systemInstall.systemInstll(params);
  if(systemInstll==="ENOTFOUND" ){
   return await res.json({status:203,msg:"数据库服务器地址错误！"}) 
  }
  if(systemInstll==="ER_ACCESS_DENIED_ERROR" ){
    return await res.json({status:203,msg:"数据库用户名或密码错误，请重新输入！"}) 
   }
   //执行数据库创建安装
    let createSqls =  await createSql.createSql(params);
    if(createSqls){
      params.installStatus='install';
      let writeJsons=  await systemInstall.writeJsons(params);
      if(writeJsons=true){
        await res.json({status:200,msg:"success"})
      }
    }
})


module.exports= router;
